<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="userPhone">
        <el-input
          v-model="queryParams.userPhone"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable size="small">
          <el-option
            v-for="dict in orderStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['platform:order:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['platform:order:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['platform:order:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['platform:order:export']"
        >订单详情
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="用户名" align="center" prop="userName"/>
      <el-table-column label="手机号" align="center" prop="userPhone"/>
      <el-table-column label="订单状态" align="center" prop="orderStatus" :formatter="orderStatusFormat"/>
      <el-table-column label="支付金额" align="center" prop="totalPay"/>
      <el-table-column label="过期时间" align="center" prop="expireTime"/>
      <el-table-column label="支付时间" align="center" prop="payedTime"/>
      <el-table-column label="创建时间" align="center" prop="createdTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['platform:order:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="goDetail(scope.row)"
            v-hasPermi="['platform:detail:list']"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="pay(scope.row)"
            v-hasPermi="['platform:order:edit']"
          >支付
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-table v-loading="loading" :data="strategyList" @selection-change="handleStrategySelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="策略名称" align="center" prop="name"/>
        <el-table-column label="描述" align="center" prop="description"/>
        <el-table-column label="价格" align="center" prop="price"/>
        <el-table-column label="类型" align="center" prop="strategyType" :formatter="strategyTypeFormat"/>
      </el-table>
      <el-table v-loading="loading" :data="robotList" @selection-change="handleRobotSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="名字" align="center" prop="name"/>
        <el-table-column label="描述" align="center" prop="description"/>
        <el-table-column label="价格" align="center" prop="price"/>
        <el-table-column label="数量" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.num" :min="1" :max="10"
                             label="数量"></el-input-number>
          </template>
        </el-table-column>
      </el-table>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            :disabled="saveDisable"
            @click="handleSave"
            v-hasPermi="['platform:order:add']"
          >保存
          </el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
  import {listOrder, getOrder, delOrder, addOrder, updateOrder, exportOrder, saveOrder, payOrder} from "@/api/platform/order";
  import {listStrategy} from "@/api/platform/strategy";
  import {listRobot, getRobot, delRobot, addRobot, updateRobot, exportRobot} from "@/api/platform/robot";

  var _self
  export default {
    name: "Order",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        saveDisable: true,
        // 总条数
        total: 0,
        // 订单表格数据
        orderList: [],
        strategyList: [],
        robotList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 订单状态字典
        orderStatusOptions: [],
        strategyTypeOptions: [],
        robotTypeOptions: [],
        userInfo: {
          userId: undefined,
          userName: undefined,
          userPhone: undefined
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          userId: undefined,
          userName: undefined,
          userPhone: undefined,
          orderStatus: undefined,
          totalPay: undefined,
          expireTime: undefined,
          payedTime: undefined,
          createdTime: undefined
        },
        queryRobotParams: {
          pageNum: 1,
          pageSize: 100,
          name: undefined,
          description: undefined,
          price: undefined,
          robotType: undefined
        },
        queryStrategyParams: {
          pageNum: 1,
          pageSize: 100,
          name: undefined,
          description: undefined,
          price: undefined,
          strategyType: undefined,
          strategyLang: undefined
        },
        // 表单参数
        form: {},
        orderSaveList: {
          strategyList: [],
          robotList: []
        },
        // 表单校验
        rules: {
          userId: [
            {required: true, message: "用户id不能为空", trigger: "blur"}
          ],
          userName: [
            {required: true, message: "用户账号不能为空", trigger: "blur"}
          ],
          userPhone: [
            {required: true, message: "用户手机号不能为空", trigger: "blur"}
          ],
          orderStatus: [
            {required: true, message: "订单状态不能为空", trigger: "blur"}
          ],
          totalPay: [
            {required: true, message: "支付金额不能为空", trigger: "blur"}
          ],
          expireTime: [
            {required: true, message: "过期时间不能为空", trigger: "blur"}
          ],
          payedTime: [
            {required: true, message: "支付时间不能为空", trigger: "blur"}
          ],
          createdTime: [
            {required: true, message: "创建时间不能为空", trigger: "blur"}
          ]
        }
      };
    },
    created() {
      _self = this
      this.userInfo.userId = this.$route.query['userId']
      this.userInfo.userName = this.$route.query['userName']
      this.userInfo.userPhone = this.$route.query['userPhone']
      this.queryParams.userId=this.userInfo.userId
      this.getList();
      this.getStrategyList();
      this.getRobotList();
      this.getDicts("plt_order_status").then(response => {
        this.orderStatusOptions = response.data;
      });
      this.getDicts("sty_strategy_type").then(response => {
        this.strategyTypeOptions = response.data;
      });
      this.getDicts("r_robot_type").then(response => {
        this.robotTypeOptions = response.data;
      });
    },
    methods: {
      /** 查询订单列表 */
      getList() {
        this.loading = true;
        listOrder(this.queryParams).then(response => {
          this.orderList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      handleSave() {
        this.orderSaveList.userInfo = this.userInfo
        console.log(this.orderSaveList)
        this.loading = true
        saveOrder(this.orderSaveList).then(response => {
          if (response.code === 200) {
            this.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          }
        });
      },
      strategyTypeFormat(row, column) {
        return this.selectDictLabel(this.strategyTypeOptions, row.strategyType);
      },
      // 机器人类型字典翻译
      robotTypeFormat(row, column) {
        return this.selectDictLabel(this.robotTypeOptions, row.robotType);
      },
      getStrategyList() {
        this.loading = true;
        listStrategy(this.queryStrategyParams).then(response => {
          this.strategyList = response.rows;
          this.loading = false;
        });
      },
      /** 查询机器人列表 */
      getRobotList() {
        this.loading = true;
        listRobot(this.queryRobotParams).then(response => {
          let robotList = response.rows;
          robotList.forEach(x => {
            x.num = 1
          })
          this.robotList = robotList;
          this.loading = false;
        });
      },

      goDetail(row) {
        this.$router.push({
          path: '/platform/platform/vip/detail',
          query: {
            userId: row.userId,
            orderId:row.orderId
          }
        })
      },
      pay(row) {
        this.loading = true;
        payOrder(row.orderId).then(res=>{
          this.msgSuccess("支付成功");
          this.loading = false;
        })
      },
      // 订单状态字典翻译
      orderStatusFormat(row, column) {
        return this.selectDictLabel(this.orderStatusOptions, row.orderStatus);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          orderId: undefined,
          userId: undefined,
          userName: undefined,
          userPhone: undefined,
          orderStatus: undefined,
          totalPay: undefined,
          expireTime: undefined,
          payedTime: undefined,
          createdTime: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.orderId)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },

      // 多选框选中数据
      handleStrategySelectionChange(selection) {
        selection.forEach(item => {
          _self.orderSaveList.strategyList.push({
            serviceId: item.strategyId,
            serviceName: item.name,
            serviceType: item.strategyType,
            serviceCategory: 'strategy'
          })
        })
        this.saveDisable = (selection.length == 0 && this.orderSaveList.robotList.length == 0)
      },

      // 多选框选中数据
      handleRobotSelectionChange(selection) {
        selection.forEach(item => {
          _self.orderSaveList.robotList.push({
            serviceId: item.robotId,
            serviceName: item.name,
            serviceType: item.robotType,
            serviceCategory: 'robot',
            num: item.num
          })
        })
        this.saveDisable = (selection.length == 0 && this.orderSaveList.strategyList.length == 0)
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加订单";
        this.orderSaveList.robotList = [];
        this.orderSaveList.strategyList = [];
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const orderId = row.orderId || this.ids
        getOrder(orderId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改订单";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.orderId != undefined) {
              updateOrder(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              addOrder(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const orderIds = row.orderId || this.ids;
        this.$confirm('是否确认删除订单编号为"' + orderIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delOrder(orderIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有订单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportOrder(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function () {
        });
      }
    }
  };
</script>
